package com.sky.blue.xmltool.xstream;

import com.sky.blue.xmltool.jaxb.Customer;
import com.sky.blue.xmltool.jaxb.User;
import com.thoughtworks.xstream.XStream;
import org.junit.Test;

import java.util.Date;

/**
 * Xstream快捷用法
 *         String xml = xStream.toXML(u1);   对象转xml
 *         User user = (User)xStream.fromXML(xml);   xml转对象
 */
public class XstreamTest {
    @Test
    public void test1(){
        User u1 = new User(3,"","asdf",new Date(),24.21);
        //java对象转xml
        XStream xStream = new XStream();
        //xStream对象设置默认安全防护，同时设置允许的类
        XStream.setupDefaultSecurity(xStream);
        xStream.allowTypes(new Class[]{User.class, Customer.class});
        //设置别名，否则会默认输出类全名
        xStream.alias("User",User.class);
        //转换xml
        String xml = xStream.toXML(u1);
        System.out.println(xml);
    }


    @Test
    public void test2(){
        XStream xStream = new XStream();
        //xStream对象设置默认安全防护，同时设置允许的类
        XStream.setupDefaultSecurity(xStream);
        xStream.allowTypes(new Class[]{User.class, Customer.class});
        xStream.alias("User", User.class);
        String xml = "<User>\n" +
                "  <userId>3</userId>\n" +
                "  <userName>qwe</userName>\n" +
                "  <password>asdf</password>\n" +
                "  <birthday>2019-11-13 13:34:27.32 UTC</birthday>\n" +
                "  <money>24.21</money>\n" +
                "</User>";
        //xml转对象
        User user = (User)xStream.fromXML(xml);
        System.out.println(user.toString());
    }

}
